package com.kuang.forkjoin;

import java.time.Duration;
import java.time.LocalDateTime;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * @program: juc
 * @description:
 * @author: 陈恩涛
 * @create: 2021-03-23 16:55
 **/
public class Test {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // PT8.547S
        // test1();

        // PT6.533S
        // test2();

        // PT0.597S
        test3();
    }

    public static void test1() {
        LocalDateTime st = LocalDateTime.now();
        Long sum = 0L;
        for (Long i = 1L; i <= 1000000000; i++) {
            sum += i;
        }
        LocalDateTime et = LocalDateTime.now();
        System.out.println("sum = " +sum+ "耗时：" + Duration.between(st, et));

    }

    public static void test2() throws ExecutionException, InterruptedException {
        LocalDateTime st = LocalDateTime.now();
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(0L, 1000000000L);

        //提交任务
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);
        Long sum = submit.get();
        LocalDateTime et = LocalDateTime.now();
        System.out.println("sum = " +sum+ "耗时：" + Duration.between(st, et));
    }

    public static void test3() {
        LocalDateTime st = LocalDateTime.now();
        long sum = LongStream.rangeClosed(1L, 1000000000L).parallel().reduce(0,Long::sum);
        LocalDateTime et = LocalDateTime.now();
        System.out.println("sum = " +sum+ "耗时：" + Duration.between(st, et));
    }
}
